package com.mcc.app.carbonEmission.service.impl;

import java.lang.reflect.Method;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.mcc.app.cache.domain.HisCol;
import com.mcc.app.cache.service.IPlcCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mcc.app.carbonEmission.mapper.ReportProductDataMapper;
import com.mcc.app.carbonEmission.domain.ReportProductData;
import com.mcc.app.carbonEmission.service.IReportProductDataService;

/**
 * 工序生产数据及排放量Service业务层处理
 *
 * @author gxy
 * @date 2025-07-04
 */
@Service
@Slf4j
public class ReportProductDataServiceImpl implements IReportProductDataService {

    @Autowired
    private ReportProductDataMapper reportProductDataMapper;

    @Autowired
    private IPlcCacheService plcCacheService;

    /**
     * 查询工序生产数据及排放量
     *
     * @param id 工序生产数据及排放量ID
     * @return 工序生产数据及排放量
     */
    @Override
    public ReportProductData selectReportProductDataById(Long id) {
        return reportProductDataMapper.selectById(id);
    }

    /**
     * 查询工序生产数据及排放量列表
     *
     * @param reportProductData 工序生产数据及排放量
     * @return 工序生产数据及排放量
     */
    @Override
    public List<ReportProductData> selectReportProductDataList(ReportProductData reportProductData) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(reportProductData)) {
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getYear()), "year", reportProductData.getYear());
            queryWrapper.like(ObjectUtil.isNotEmpty(reportProductData.getProcessName()), "process_name", reportProductData.getProcessName());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getItemRemark()), "item_remark", reportProductData.getItemRemark());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getInfoItem()), "info_item", reportProductData.getInfoItem());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getItemDesc()), "item_desc", reportProductData.getItemDesc());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getUnit()), "unit", reportProductData.getUnit());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth1()), "month1", reportProductData.getMonth1());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth2()), "month2", reportProductData.getMonth2());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth3()), "month3", reportProductData.getMonth3());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth4()), "month4", reportProductData.getMonth4());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth5()), "month5", reportProductData.getMonth5());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth6()), "month6", reportProductData.getMonth6());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth7()), "month7", reportProductData.getMonth7());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth8()), "month8", reportProductData.getMonth8());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth9()), "month9", reportProductData.getMonth9());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth10()), "month10", reportProductData.getMonth10());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth11()), "month11", reportProductData.getMonth11());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMonth12()), "month12", reportProductData.getMonth12());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getYearvalue()), "yearValue", reportProductData.getYearvalue());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getGetWay()), "get_way", reportProductData.getGetWay());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getIsequip()), "isEquip", reportProductData.getIsequip());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getSource()), "source", reportProductData.getSource());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getMaterial()), "material", reportProductData.getMaterial());
            queryWrapper.eq(ObjectUtil.isNotEmpty(reportProductData.getInput()), "input", reportProductData.getInput());
        }
        return reportProductDataMapper.selectList(queryWrapper);
    }

    /**
     * 新增工序生产数据及排放量
     *
     * @param reportProductData 工序生产数据及排放量
     * @return 结果
     */
    @Override
    public int insertReportProductData(ReportProductData reportProductData) {
        return reportProductDataMapper.insert(reportProductData);
    }

    /**
     * 修改工序生产数据及排放量
     *
     * @param reportProductData 工序生产数据及排放量
     * @return 结果
     */
    @Override
    public int updateReportProductData(ReportProductData reportProductData) {
        int result = reportProductDataMapper.updateById(reportProductData);
        generateProductData(false);
        return result;
    }

    /**
     * 修改工序生产数据及排放量
     *
     * @param reportProductDataList 工序生产数据及排放量
     * @return 结果
     */
    @Override
    public int updateReportProductDataList(List<ReportProductData> reportProductDataList) {
        int result = 0;
        if(reportProductDataList!= null){
            for(int i = 0;i<reportProductDataList.size(); i++){
                //小数点处理
                result = reportProductDataMapper.updateById(reportProductDataList.get(i));
            }
            generateProductData(false);
        }


        return result;
    }

    /**
     * 删除工序生产数据及排放量
     *
     * @param id 工序生产数据及排放量ID
     * @return 结果
     */
    @Override
    public int deleteReportProductDataById(Long id) {
        return reportProductDataMapper.deleteById(id);
    }

    /**
     * 批量删除工序生产数据及排放量
     *
     * @param ids 工序生产数据及排放量ID
     * @return 结果
     */
    @Override
    public int deleteReportProductDataByIds(Long[] ids) {
        if (ids.length == 0) return 0;
        return reportProductDataMapper.deleteBatchIds(ListUtil.toList(ids));
    }

    //定时会调用，前端修改也会掉用，测量值在定时任务中提前搜索记录;修改原则：凌晨刷新当月的测量值数据，也就会重新计算（可以不用计算前面月份得）；界面修改得话只按照修改值计算。
    @Override
    public void generateProductData(boolean isSearch){
        LocalDate curDate = LocalDate.now(); // 当前日期
        LocalDate previousDate = curDate.minusDays(1);
        Date endDate = new Date();
        // 获取本月的第一天
        LocalDate firstDayOfMonth = curDate.withDayOfMonth(1);
        // 获取当前月份的第二天的日期（不考虑年份和月份，只考虑日）
        LocalDate secondDayOfMonth = curDate.withDayOfMonth(2);
        int year = curDate.getYear();
        int month = curDate.getMonthValue();
        int day = curDate.getDayOfMonth();
        // 获取上个月的第一天（上个月开始）
        LocalDate startOfLastMonth = curDate.with(TemporalAdjusters.firstDayOfMonth())
                .minusMonths(1);
        // 获取上个月最后一天（上个月结束）
        LocalDate endOfLastMonth = startOfLastMonth.with(TemporalAdjusters.lastDayOfMonth());
        // 将日期时间转换为LocalDateTime，以便可以包含时间信息（如果需要）
        LocalDateTime startOfLastMonthDateTime = startOfLastMonth.atStartOfDay(); // 上个月开始的时间点，默认为00:00:00
        LocalDateTime endOfLastMonthDateTime = endOfLastMonth.atTime(LocalTime.MAX); // 上个月结束的时间点，默认为23:59:59.999999999

        ReportProductData condition = new ReportProductData();
        condition.setYear(Convert.toStr(year));
        List<ReportProductData> dataList = selectReportProductDataList(condition);
        boolean isUpdate = true;
        if(null == dataList || dataList.size() == 0){
            //新增
            isUpdate = false;
            int oldYear = year-1;
            condition.setYear(Convert.toStr(oldYear));
            dataList = selectReportProductDataList(condition);
            //1-1 00：00：05读取得是上个月最后一天的数据，先将上个月最后一天得数据累计上并更新数据库
            {
                //设置值
                ReportProductData ession1 = dataList.stream().filter(item->item.getItemRemark().equals("emission1")).collect(Collectors.toList()).get(0);
                ReportProductData input1 = dataList.stream().filter(item->item.getItemRemark().equals ("input1")).collect(Collectors.toList()).get(0);
                ReportProductData fever1 = dataList.stream().filter(item->item.getItemRemark().equals("fever1")).collect(Collectors.toList()).get(0);
                ReportProductData carbon1 = dataList.stream().filter(item->item.getItemRemark().equals("carbon1")).collect(Collectors.toList()).get(0);


                ReportProductData ession2 = dataList.stream().filter(item->item.getItemRemark().equals("emission2")).collect(Collectors.toList()).get(0);
                ReportProductData input2 = dataList.stream().filter(item->item.getItemRemark().equals("input2")).collect(Collectors.toList()).get(0);
                ReportProductData fever2 = dataList.stream().filter(item->item.getItemRemark().equals("fever2")).collect(Collectors.toList()).get(0);
                ReportProductData carbon2 = dataList.stream().filter(item->item.getItemRemark().equals("carbon2")).collect(Collectors.toList()).get(0);


                ReportProductData ession3 = dataList.stream().filter(item->item.getItemRemark().equals("emission3")).collect(Collectors.toList()).get(0);
                ReportProductData input3 = dataList.stream().filter(item->item.getItemRemark().equals("input3")).collect(Collectors.toList()).get(0);
                ReportProductData fever3 = dataList.stream().filter(item->item.getItemRemark().equals("fever3")).collect(Collectors.toList()).get(0);
                ReportProductData carbon3 = dataList.stream().filter(item->item.getItemRemark().equals("carbon3")).collect(Collectors.toList()).get(0);

                ReportProductData esj = dataList.stream().filter(item->item.getItemRemark().equals("esj")).collect(Collectors.toList()).get(0);
                ReportProductData output = dataList.stream().filter(item->item.getItemRemark().equals("output")).collect(Collectors.toList()).get(0);
                ReportProductData unitEmission = dataList.stream().filter(item->item.getItemRemark().equals("unitEmission")).collect(Collectors.toList()).get(0);
                try{
                    {
                        Double cacheResult = Convert.toDouble(plcCacheService.getRedisCache("st2_previous14_daily"), 0.0);
                        input1.setMonth12(input1.getMonth12()+cacheResult);
                        input1.setYearvalue(input1.getYearvalue() + cacheResult);
                        //FC 化石燃料1, ×NCV ar,1 ,×CC 1 ×44/12（下面三个值相乘再乘以44/12）
                        Double result12 = input1.getMonth12() * fever1.getMonth12()*carbon1.getMonth12()*44/12;//12月份的新值
                        Double diff12 = result12 - ession1.getMonth12();//12月份的差值
                        ession1.setMonth12(result12);
                        ession1.setYearvalue(ession1.getYearvalue() + diff12);
                        updateReportProductData(input1);
                        updateReportProductData(ession1);
                    }
                    {
                        Double cacheResult = Convert.toDouble(plcCacheService.getRedisCache("st2_previous15_daily"), 0.0);
                        input2.setMonth12(input2.getMonth12()+cacheResult);
                        input2.setYearvalue(input2.getYearvalue() + cacheResult);
                        //FC 化石燃料1, ×NCV ar,1 ,×CC 1 ×44/12（下面三个值相乘再乘以44/12）
                        Double result12 = input2.getMonth12() * fever2.getMonth12()*carbon2.getMonth12()*44/12;//12月份的新值
                        Double diff12 = result12 - ession2.getMonth12();//12月份的差值
                        ession2.setMonth12(result12);
                        ession2.setYearvalue(ession2.getYearvalue() + diff12);
                        updateReportProductData(input2);
                        updateReportProductData(ession2);
                    }
                    {

                        //高炉煤气找出本月第一条数据，当前数据减去第一条数据
                        Double startInput3 = 0.0;
                        Double endInput3 = 0.0;
                        List<Map<String, Object>> hisDataList = plcCacheService.getHisTopNData("st3_gmqzg_lf", 1, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime), 5, "asc");
                        List<HisCol> valueList = (List<HisCol>)hisDataList.get(0).get("list");
                        if(valueList != null&& valueList.size() != 0){
                            startInput3 = valueList.get(0).getValue();
                        }

                        List<Map<String, Object>> endDataList = plcCacheService.getHisTopNData("st3_gmqzg_lf", 1, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime), 5, "desc");
                        List<HisCol> endValueList = (List<HisCol>)endDataList.get(0).get("list");
                        if(endValueList != null&& endValueList.size() != 0){
                            endInput3 = endValueList.get(0).getValue();
                        }
                        if(startInput3 > endInput3)
                        {
                            endInput3 = Convert.toDouble(plcCacheService.getRedisCache("st3_gmqzg_lf"), 0.0);
                        }
                        Double allFlow = endInput3-startInput3;//本月累计流量
                        //计算本月平均压力和温度
                        Double avgPressure = 0.0;
                        Double avgTemp = 0.0;
                        List<Map<String, Object>> data2List = plcCacheService.getHisChart("st3_gmqzg_p,st3_gmqzg_t", 3, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime));
                        for(int k = 0;k<data2List.size();k++){
                            if(data2List.get(k).get("code").equals("st3_gmqzg_p")){//压力
                                List<HisCol> pValueList = (List<HisCol>)data2List.get(k).get("list");
                                if(pValueList != null && pValueList.size() != 0){
                                    Double allPressure = 0.0;
                                    for(int l = 0; l <pValueList.size();l++){
                                        allPressure += pValueList.get(l).getValue();
                                    }
                                    avgPressure = allPressure / pValueList.size();
                                }
                            }else if(data2List.get(k).get("code").equals("st3_gmqzg_t")){//温度
                                List<HisCol> tValueList = (List<HisCol>)data2List.get(k).get("list");
                                if(tValueList != null && tValueList.size() != 0){
                                    Double allTemp = 0.0;
                                    for(int l = 0; l <tValueList.size();l++){
                                        allTemp += tValueList.get(l).getValue();
                                    }
                                    avgTemp = allTemp / tValueList.size();
                                }
                            }
                        }
//                    实际工况：需已知实际 压力 P（单位：kPa）和 温度 T（单位：K，即 T(°C)+273.15）
//                    标准状态：Pstd​=101.325kPa，Tstd​=273.15K（0°C）
//                    Vstd​(Nm3)=V⋅P/Pstd​⋅Tstd/T​​
                        Double stdP = 101.325;
                        Double stdT = 273.15;
                        Double lastResult = allFlow * avgPressure/stdP * stdT/(avgTemp + 273.15);
                        Double diff12 = lastResult - input3.getMonth12();
                        input3.setMonth12(lastResult);
                        input3.setYearvalue(input3.getYearvalue() + diff12);
                        Double result3 = input3.getMonth12() * fever3.getMonth12()*carbon3.getMonth12()*44/12;
                        Double yearDiff12 = result3 - ession3.getMonth12();
                        ession3.setMonth12(result3);
                        ession3.setYearvalue(ession3.getYearvalue() + yearDiff12);
                        updateReportProductData(input3);
                        updateReportProductData(ession3);


                    }
                    {
                        //Esj
                        Double all = ession1.getMonth12() + ession2.getMonth12() + ession3.getMonth12();
                        Double diff12 = all - esj.getMonth12();
                        esj.setMonth12(all);
                        esj.setYearvalue(esj.getYearvalue() + diff12);
                        updateReportProductData(esj);
                    }
                    {
                        Double startOutput = 0.0;
                        Double endOutput = 0.0;
                        {
                            List<Map<String, Object>> hisDataList = plcCacheService.getHisTopNData("st4_c_c1sjk_lj", 1, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime), 5, "asc");
                            List<HisCol> valueList = (List<HisCol>)hisDataList.get(0).get("list");
                            if(valueList != null&& valueList.size() != 0){
                                startOutput = valueList.get(0).getValue();
                            }
                        }
                        {
                            List<Map<String, Object>> endDataList = plcCacheService.getHisTopNData("st4_c_c1sjk_lj", 1, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime), 5, "desc");
                            List<HisCol> endValueList = (List<HisCol>)endDataList.get(0).get("list");
                            if(endValueList != null&& endValueList.size() != 0){
                                endOutput = endValueList.get(0).getValue();
                            }
                        }
                        if(endOutput < startOutput)
                        {
                            endOutput = Convert.toDouble(plcCacheService.getRedisCache("st4_c_c1sjk_lj"), 0.0);
                        }
                        Double diff12 = endOutput - output.getMonth12();
                       output.setMonth12(endOutput);
                       output.setYearvalue(output.getYearvalue() + diff12);
                       updateReportProductData(output);
                    }
                    //烧结工序单位产品碳排放量
                    {
                        //工序单位产品碳排放量
                        Double perUnit = 0.0;
                        if(output.getMonth12() > 0.0){
                             perUnit = esj.getMonth12()/output.getMonth12();
                        }
                        Double diff12 = perUnit - esj.getMonth12();
                        unitEmission.setMonth12(perUnit);
                        unitEmission.setYearvalue(esj.getYearvalue() + diff12);
                        updateReportProductData(unitEmission);
                    }


                }catch (Exception ex)
                {
                    log.info("ex is "+ex.getMessage());
                }

            }
            //将默认数据全部置空重新记算
            if(null != dataList && dataList.size() != 0){
                for(int i = 0;i<dataList.size();i++)
                {
                    dataList.get(i).setId(null);
                    dataList.get(i).setYear(Convert.toStr(year));
                    dataList.get(i).setMonth1(null);
                    dataList.get(i).setMonth2(null);
                    dataList.get(i).setMonth3(null);
                    dataList.get(i).setMonth4(null);
                    dataList.get(i).setMonth5(null);
                    dataList.get(i).setMonth6(null);
                    dataList.get(i).setMonth7(null);
                    dataList.get(i).setMonth8(null);
                    dataList.get(i).setMonth9(null);
                    dataList.get(i).setMonth10(null);
                    dataList.get(i).setMonth11(null);
                    dataList.get(i).setMonth12(null);
                    dataList.get(i).setYearvalue(null);
                }
            }

        }
//设置值
        ReportProductData ession1 = dataList.stream().filter(item->item.getItemRemark().equals("emission1")).collect(Collectors.toList()).get(0);
        ReportProductData input1 = dataList.stream().filter(item->item.getItemRemark().equals ("input1")).collect(Collectors.toList()).get(0);
        ReportProductData fever1 = dataList.stream().filter(item->item.getItemRemark().equals("fever1")).collect(Collectors.toList()).get(0);
        ReportProductData carbon1 = dataList.stream().filter(item->item.getItemRemark().equals("carbon1")).collect(Collectors.toList()).get(0);

        ReportProductData ession2 = dataList.stream().filter(item->item.getItemRemark().equals("emission2")).collect(Collectors.toList()).get(0);
        ReportProductData input2 = dataList.stream().filter(item->item.getItemRemark().equals("input2")).collect(Collectors.toList()).get(0);
        ReportProductData fever2 = dataList.stream().filter(item->item.getItemRemark().equals("fever2")).collect(Collectors.toList()).get(0);
        ReportProductData carbon2 = dataList.stream().filter(item->item.getItemRemark().equals("carbon2")).collect(Collectors.toList()).get(0);


        ReportProductData ession3 = dataList.stream().filter(item->item.getItemRemark().equals("emission3")).collect(Collectors.toList()).get(0);
        ReportProductData input3 = dataList.stream().filter(item->item.getItemRemark().equals("input3")).collect(Collectors.toList()).get(0);
        ReportProductData fever3 = dataList.stream().filter(item->item.getItemRemark().equals("fever3")).collect(Collectors.toList()).get(0);
        ReportProductData carbon3 = dataList.stream().filter(item->item.getItemRemark().equals("carbon3")).collect(Collectors.toList()).get(0);

        ReportProductData esj = dataList.stream().filter(item->item.getItemRemark().equals("esj")).collect(Collectors.toList()).get(0);
        ReportProductData output = dataList.stream().filter(item->item.getItemRemark().equals("output")).collect(Collectors.toList()).get(0);
        ReportProductData unitEmission = dataList.stream().filter(item->item.getItemRemark().equals("unitEmission")).collect(Collectors.toList()).get(0);

        try{
            boolean isFever2 = true;//记录第2种化石燃料的收到基低位发热量是否使用的是缺省值 有一个不一样则就改变
            boolean isFever3 = true;//记录第3种化石燃料的收到基低位发热量是否使用的是缺省值 有一个不一样则就改变

            //只会根据历史数据获取当月的测量值；其他月在当时已经计算过，若中途修改则直接按照修改值计算即可，若改为空有缺省值就按照缺省值去算没有就当是0去算。测量值目前都不让修改
            for(int i = 1; i<= month;i++)
            {


                    //第一种化石燃料
                    //先设置默认值
                    Method getter = ReportProductData.class.getMethod("getMonth"+i);
                    Object resultInput1 = getter.invoke(input1); // 调用getter方法 测量值不让修改
                    Object resultFever1 = getter.invoke(fever1); // 28.435GJ/t 调用getter方法  却省值若为空或者0，则使用缺省值
                    Object resultCarbon1 = getter.invoke(carbon1); //0.02942tC/GJ 调用getter方法 却省值若为空或者0，则使用缺省值
                    Method setter = ReportProductData.class.getMethod("setMonth"+i, Double.class);
                    if( i == month && isSearch && day != 1)//为true定时任务掉用需要搜索历史数据刷新当月的测量值
                    {
                        //焦粉和煤粉，若刚启动数据为空或0，则需要去查询历史数据统计本月每天的数据量之和，若非空则加上当前前一日即可
                        if((resultInput1 == null ||  Convert.toDouble(resultInput1) == 0.0 ) && day > 2){
                            List<Map<String, Object>> hisDataList = plcCacheService.getHisIntervalHisData("st2_previous14_daily", 1, convertLocalDateToDate(secondDayOfMonth), endDate, 0, 0, 3);
                            Double allInput1 = 0.0;
                            List<HisCol> valueList = (List<HisCol>)hisDataList.get(0).get("list");
                            if(valueList != null){
                                for(int k = 0; k<valueList.size();k++){
                                    allInput1 += Convert.toDouble(valueList.get(k).getValue(), 0.0);
                                }
                                setter.invoke(input1, allInput1);
                            }

                        }else if( day > 1){
                            Double cacheResult = Convert.toDouble(plcCacheService.getRedisCache("st2_previous14_daily"), 0.0);
                            setter.invoke(input1, Convert.toDouble(resultInput1, 0.0)+cacheResult);
                        }

                    }else if(isSearch && month > 1 && i == month - 1 && day ==1){//如果是非1月的其他月份的1日，需要将当下累计值累积到上个月的数据中
                        Double cacheResult = Convert.toDouble(plcCacheService.getRedisCache("st2_previous14_daily"), 0.0);
                        setter.invoke(input1, Convert.toDouble(resultInput1, 0.0)+cacheResult);
                    }


                    if(resultFever1 == null || Convert.toDouble(resultFever1) == 0.0){
                        setter.invoke(fever1, 28.435);
                    }

                    if(resultCarbon1 == null || Convert.toDouble(resultCarbon1) == 0.0){
                        setter.invoke(carbon1, 0.02942);
                    }
                    //FC 化石燃料1, ×NCV ar,1 ,×CC 1 ×44/12（下面三个值相乘再乘以44/12）
                    Double result1 = Convert.toDouble(getter.invoke(input1), 0.0) * Convert.toDouble(getter.invoke(fever1), 0.0)*Convert.toDouble(getter.invoke(carbon1), 0.0)*44/12;
                    setter.invoke(ession1, result1);


                    //第二种化石燃料
                    //先设置默认值

                    Object resultInput2 = getter.invoke(input2); // 调用getter方法 测量值不让修改
                    Object resultFever2 = getter.invoke(fever2); // 25.024GJ/t 调用getter方法  却省值若为空或者0，则使用缺省值
                    Object resultCarbon2 = getter.invoke(carbon2); //0.02749tC/GJ 调用getter方法 却省值若为空或者0，则使用缺省值
                    if(resultFever2 == null || Convert.toDouble(resultFever2, 0.0) == 0.0){
                        setter.invoke(fever2, 25.024);
                    }else if(Convert.toDouble(resultFever2, 0.0) != 25.024){
                        isFever2 = false;
                    }
                    if(resultCarbon2 == null || Convert.toDouble(resultCarbon2) == 0.0){
                        setter.invoke(carbon2, 0.02749);
                    }

                if( i == month && isSearch && day != 1)//为true定时任务掉用需要搜索历史数据刷新当月的测量值
                {
                    //焦粉和煤粉，若刚启动数据为空或0，则需要去查询历史数据统计本月每天的数据量之和，若非空则加上当前前一日即可
                    if((resultInput2 == null ||  Convert.toDouble(resultInput2) == 0.0 ) && day > 2){
                        List<Map<String, Object>> hisDataList = plcCacheService.getHisIntervalHisData("st2_previous15_daily", 1, convertLocalDateToDate(secondDayOfMonth), endDate, 0, 0, 3);
                        Double allInput2 = 0.0;
                        List<HisCol> valueList = (List<HisCol>)hisDataList.get(0).get("list");
                        if(valueList != null){
                            for(int k = 0; k<valueList.size();k++){
                                allInput2 += valueList.get(k).getValue();
                            }
                            setter.invoke(input2, allInput2);
                        }

                    }else if( day > 1){
                        Double cacheResult = Convert.toDouble(plcCacheService.getRedisCache("st2_previous15_daily"), 0.0);
                        setter.invoke(input2, Convert.toDouble(resultInput2, 0.0)+cacheResult);
                    }

                }else if(isSearch && month > 1 && i == month - 1 && day ==1){//如果是非1月的其他月份的1日，需要将当下累计值累积到上个月的数据中
                    Double cacheResult = Convert.toDouble(plcCacheService.getRedisCache("st2_previous15_daily"), 0.0);
                    setter.invoke(input2, Convert.toDouble(resultInput2, 0.0)+cacheResult);
                }
                    //FC 化石燃料2 ×NCV ar,2 ×CC 2 ×44/12（下面三个值相乘再乘以44/12）
                    Double result2 = Convert.toDouble(getter.invoke(input2), 0.0) * Convert.toDouble(getter.invoke(fever2), 0.0)*Convert.toDouble(getter.invoke(carbon2), 0.0)*44/12;
                    setter.invoke(ession2, result2);


                    //第三种化石燃料
                    //先设置默认值

                    Object resultInput3 = getter.invoke(input3); // 调用getter方法 测量值不让修改
                if( i == month && isSearch && day != 1)//为true定时任务掉用需要搜索历史数据刷新当月的测量值
                {
                    //高炉煤气找出本月第一条数据，当前数据减去第一条数据

                        List<Map<String, Object>> hisDataList = plcCacheService.getHisTopNData("st3_gmqzg_lf", 1, convertLocalDateToDate(firstDayOfMonth), endDate, 5, "asc");
                        Double startInput3 = 0.0;
                        List<HisCol> valueList = (List<HisCol>)hisDataList.get(0).get("list");
                        if(valueList != null&& valueList.size() != 0){
                            startInput3 = valueList.get(0).getValue();
                        }
                        Double cacheResult = Convert.toDouble(plcCacheService.getRedisCache("st3_gmqzg_lf"), 0.0);
                        Double allFlow = cacheResult-startInput3;//本月累计流量
                    //计算本月平均压力和温度
                    Double avgPressure = 0.0;
                    Double avgTemp = 0.0;
                    List<Map<String, Object>> data2List = plcCacheService.getHisChart("st3_gmqzg_p,st3_gmqzg_t", 3, convertLocalDateToDate(firstDayOfMonth), endDate);
                    for(int k = 0;k<data2List.size();k++){
                        if(data2List.get(k).get("code").equals("st3_gmqzg_p")){//压力
                            List<HisCol> pValueList = (List<HisCol>)data2List.get(k).get("list");
                            if(pValueList != null && pValueList.size() != 0){
                                Double allPressure = 0.0;
                                for(int l = 0; l <pValueList.size();l++){
                                    allPressure += pValueList.get(l).getValue();
                                }
                                avgPressure = allPressure / pValueList.size();
                            }
                        }else if(data2List.get(k).get("code").equals("st3_gmqzg_t")){//温度
                            List<HisCol> tValueList = (List<HisCol>)data2List.get(k).get("list");
                            if(tValueList != null && tValueList.size() != 0){
                                Double allTemp = 0.0;
                                for(int l = 0; l <tValueList.size();l++){
                                    allTemp += tValueList.get(l).getValue();
                                }
                                avgTemp = allTemp / tValueList.size();
                            }
                        }
                    }
//                    实际工况：需已知实际 压力 P（单位：kPa）和 温度 T（单位：K，即 T(°C)+273.15）
//                    标准状态：Pstd​=101.325kPa，Tstd​=273.15K（0°C）
//                    Vstd​(Nm3)=V⋅P/Pstd​⋅Tstd/T​​
                    Double stdP = 101.325;
                    Double stdT = 273.15;
                    Double lastResult = allFlow * avgPressure/stdP * stdT/(avgTemp + 273.15);
                    setter.invoke(input3, lastResult);


                }else if(isSearch && month > 1 && i == month - 1 && day ==1){

                    //高炉煤气找出本月第一条数据，当前数据减去第一条数据
                    Double startInput3 = 0.0;
                    Double endInput3 = 0.0;
                    List<Map<String, Object>> hisDataList = plcCacheService.getHisTopNData("st3_gmqzg_lf", 1, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime), 5, "asc");
                    List<HisCol> valueList = (List<HisCol>)hisDataList.get(0).get("list");
                    if(valueList != null&& valueList.size() != 0){
                        startInput3 = valueList.get(0).getValue();
                    }

                    List<Map<String, Object>> endDataList = plcCacheService.getHisTopNData("st3_gmqzg_lf", 1, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime), 5, "desc");
                    List<HisCol> endValueList = (List<HisCol>)endDataList.get(0).get("list");
                    if(endValueList != null&& endValueList.size() != 0){
                        endInput3 = endValueList.get(0).getValue();
                    }
                    if(startInput3 > endInput3)
                    {
                        endInput3 = Convert.toDouble(plcCacheService.getRedisCache("st3_gmqzg_lf"), 0.0);
                    }
                    Double allFlow = endInput3-startInput3;//本月累计流量
                    //计算本月平均压力和温度
                    Double avgPressure = 0.0;
                    Double avgTemp = 0.0;
                    List<Map<String, Object>> data2List = plcCacheService.getHisChart("st3_gmqzg_p,st3_gmqzg_t", 3, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime));
                    for(int k = 0;k<data2List.size();k++){
                        if(data2List.get(k).get("code").equals("st3_gmqzg_p")){//压力
                            List<HisCol> pValueList = (List<HisCol>)data2List.get(k).get("list");
                            if(pValueList != null && pValueList.size() != 0){
                                Double allPressure = 0.0;
                                for(int l = 0; l <pValueList.size();l++){
                                    allPressure += pValueList.get(l).getValue();
                                }
                                avgPressure = allPressure / pValueList.size();
                            }
                        }else if(data2List.get(k).get("code").equals("st3_gmqzg_t")){//温度
                            List<HisCol> tValueList = (List<HisCol>)data2List.get(k).get("list");
                            if(tValueList != null && tValueList.size() != 0){
                                Double allTemp = 0.0;
                                for(int l = 0; l <tValueList.size();l++){
                                    allTemp += tValueList.get(l).getValue();
                                }
                                avgTemp = allTemp / tValueList.size();
                            }
                        }
                    }
//                    实际工况：需已知实际 压力 P（单位：kPa）和 温度 T（单位：K，即 T(°C)+273.15）
//                    标准状态：Pstd​=101.325kPa，Tstd​=273.15K（0°C）
//                    Vstd​(Nm3)=V⋅P/Pstd​⋅Tstd/T​​
                    Double stdP = 101.325;
                    Double stdT = 273.15;
                    Double lastResult = allFlow * avgPressure/stdP * stdT/(avgTemp + 273.15);
                    setter.invoke(input3, lastResult);


                }
                    Object resultFever3 = getter.invoke(fever3); // 33.000*10000GJ/t 调用getter方法  却省值若为空或者0，则使用缺省值
                    Object resultCarbon3 = getter.invoke(carbon3); //0.07080tC/GJ 调用getter方法 却省值若为空或者0，则使用缺省值
                    if(resultFever3 == null || Convert.toDouble(resultFever3, 0.0) == 0.0){
                        setter.invoke(fever3, 33.0);
                    }else if(Convert.toDouble(resultFever3, 0.0) != 33.0){
                        isFever3 = false;
                    }
                    if(resultCarbon3 == null || Convert.toDouble(resultCarbon3, 0.0) == 0.0){
                        setter.invoke(carbon3, 0.07080);
                    }
                    //FC 化石燃料3 ×NCV ar,3 ×CC 3 ×44/12（下面三个值相乘再乘以44/12）
                    Double result3 = Convert.toDouble(getter.invoke(input3), 0.0) * Convert.toDouble(getter.invoke(fever3), 0.0)*Convert.toDouble(getter.invoke(carbon3), 0.0)*44/12;
                    setter.invoke(ession3, result3);

                    //Esj
                    setter.invoke(esj, result1+result2+result3);
                    //工序产品质量 测量值，但需要累加
                    Double resultOutput = Convert.toDouble(getter.invoke(output), 0.0);
                    if( i == month && isSearch && day != 1)//为true定时任务掉用需要搜索历史数据刷新当月的测量值
                    {
                        //产量直接用成1烧结矿累计,找出本月第一条数据，当前数据减去第一条数据

                        List<Map<String, Object>> hisDataList = plcCacheService.getHisTopNData("st4_c_c1sjk_lj", 1, convertLocalDateToDate(firstDayOfMonth), endDate, 5, "asc");
                        Double startOutput = 0.0;
                        List<HisCol> valueList = (List<HisCol>)hisDataList.get(0).get("list");
                        if(valueList != null&& valueList.size() != 0){
                            startOutput = valueList.get(0).getValue();
                        }
                        Double cacheResult = Convert.toDouble(plcCacheService.getRedisCache("st4_c_c1sjk_lj"), 0.0);
                        setter.invoke(output, cacheResult-startOutput);


                    }else if(isSearch && month > 1 && i == month - 1 && day ==1){

                        Double startOutput = 0.0;
                        Double endOutput = 0.0;
                        {
                            List<Map<String, Object>> hisDataList = plcCacheService.getHisTopNData("st4_c_c1sjk_lj", 1, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime), 5, "asc");
                            List<HisCol> valueList = (List<HisCol>)hisDataList.get(0).get("list");
                            if(valueList != null&& valueList.size() != 0){
                                startOutput = valueList.get(0).getValue();
                            }
                        }
                        {
                            List<Map<String, Object>> endDataList = plcCacheService.getHisTopNData("st4_c_c1sjk_lj", 1, convertLocalDateTimeToDate(startOfLastMonthDateTime), convertLocalDateTimeToDate(endOfLastMonthDateTime), 5, "desc");
                            List<HisCol> endValueList = (List<HisCol>)endDataList.get(0).get("list");
                            if(endValueList != null&& endValueList.size() != 0){
                                endOutput = endValueList.get(0).getValue();
                            }
                        }

                        if(endOutput < startOutput)
                        {
                            endOutput = Convert.toDouble(plcCacheService.getRedisCache("st4_c_c1sjk_lj"), 0.0);
                        }
                        setter.invoke(output, endOutput-startOutput);
                    }
                    //工序单位产品碳排放量
                    if(Convert.toDouble(getter.invoke(output), 0.0) > 0.0){
                    Double perUnit = Convert.toDouble(getter.invoke(esj), 0.0)/Convert.toDouble(getter.invoke(output), 0.0);
                    setter.invoke(unitEmission, perUnit);
                     }else{
                        setter.invoke(unitEmission, 0.0);
                    }


                    //全年设置
                    if(i == 1){//设置全年
                        input1.setYearvalue(Convert.toDouble(getter.invoke(input1), 0.0));
                        fever1.setYearvalue(Convert.toDouble(getter.invoke(fever1), 0.0));
                        carbon1.setYearvalue(Convert.toDouble(getter.invoke(carbon1), 0.0));
                        ession1.setYearvalue(Convert.toDouble(getter.invoke(ession1), 0.0));

                        input2.setYearvalue(Convert.toDouble(getter.invoke(input2), 0.0));
                        fever2.setYearvalue(Convert.toDouble(getter.invoke(fever2), 0.0));
                        carbon2.setYearvalue(Convert.toDouble(getter.invoke(carbon2), 0.0));
                        ession2.setYearvalue(Convert.toDouble(getter.invoke(ession2), 0.0));

                        input3.setYearvalue(Convert.toDouble(getter.invoke(input3), 0.0));
                        fever3.setYearvalue(Convert.toDouble(getter.invoke(fever3), 0.0));
                        carbon3.setYearvalue(Convert.toDouble(getter.invoke(carbon3), 0.0));
                        ession3.setYearvalue(Convert.toDouble(getter.invoke(ession3), 0.0));

                        esj.setYearvalue(Convert.toDouble(getter.invoke(esj), 0.0));
                        output.setYearvalue(Convert.toDouble(getter.invoke(output), 0.0));
                        unitEmission.setYearvalue(Convert.toDouble(getter.invoke(unitEmission), 0.0));

                    } else if(i > 1){//设置全年
                        input1.setYearvalue(input1.getYearvalue()+ Convert.toDouble(getter.invoke(input1), 0.0));
                        fever1.setYearvalue(fever1.getYearvalue()+ Convert.toDouble(getter.invoke(fever1), 0.0));
                        carbon1.setYearvalue(carbon1.getYearvalue()+ Convert.toDouble(getter.invoke(carbon1), 0.0));
                        ession1.setYearvalue(ession1.getYearvalue()+ Convert.toDouble(getter.invoke(ession1), 0.0));

                        input2.setYearvalue(input2.getYearvalue()+ Convert.toDouble(getter.invoke(input2), 0.0));
                        fever2.setYearvalue(fever2.getYearvalue()+ Convert.toDouble(getter.invoke(fever2), 0.0));
                        carbon2.setYearvalue(carbon2.getYearvalue()+ Convert.toDouble(getter.invoke(carbon2), 0.0));
                        ession2.setYearvalue(ession2.getYearvalue()+ Convert.toDouble(getter.invoke(ession2), 0.0));

                        input3.setYearvalue(input3.getYearvalue()+ Convert.toDouble(getter.invoke(input3), 0.0));
                        fever3.setYearvalue(fever3.getYearvalue()+ Convert.toDouble(getter.invoke(fever3), 0.0));
                        carbon3.setYearvalue(carbon3.getYearvalue()+ Convert.toDouble(getter.invoke(carbon3), 0.0));
                        ession3.setYearvalue(ession3.getYearvalue()+Convert.toDouble(getter.invoke(ession3), 0.0));

                        esj.setYearvalue(esj.getYearvalue() + Convert.toDouble(getter.invoke(esj), 0.0));
                        output.setYearvalue(output.getYearvalue()+ Convert.toDouble(getter.invoke(output), 0.0));
                        unitEmission.setYearvalue(unitEmission.getYearvalue() + Convert.toDouble(getter.invoke(unitEmission), 0.0));
                    }

            }
            if(!isFever2){
                fever2.setGetWay("企业层级数据");
            }else{
                fever2.setGetWay("缺省值");
            }
            if(!isFever3){
                fever3.setGetWay("企业层级数据");
            }else{
                fever3.setGetWay("缺省值");
            }
            //存储
            for(int j = 0; j<dataList.size();j++)
            {
                //处理数据，保留位数
                ReportProductData item = dataList.get(j);
                displayData(item);
                if(isUpdate){

                    reportProductDataMapper.updateById(item);
                }else{
                    reportProductDataMapper.insert(item);
                }

            }

        }catch (Exception ex){
            log.error("ex is "+ex);
        }






    }

    public static Date convertLocalDateToDate(LocalDate localDate) {
        // 将LocalDate转换为ZonedDateTime，指定时间为一天的开始
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

        // 将ZonedDateTime转换为Instant
        Instant instant = zonedDateTime.toInstant();

        // 将Instant转换为Date
        Date date = Date.from(instant);

        return date;
    }

    public static Date convertLocalDateTimeToDate(LocalDateTime localDateTime) {
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
        Instant instant = zonedDateTime.toInstant();
        Date date = Date.from(instant);

        return date;
    }

//    各参数按四舍五入保留小数位如下 ：
//    a）固体化石燃料、液体化石燃料输入量、输出量、消耗量单位为 t，气体化石燃料输入量、输出量、消耗量单位为 10 4 Nm 3 ，保留到小数点后两位；
//    b）固体化石燃料、液体化石燃料低位发热量单位为 GJ/t，气体化石燃料低位发热量单位为 GJ/10 4 Nm 3 ，保留到小数点后三位；
//    c）单位热值含碳量单位为 tC/GJ，保留到小数点后五位；
//    d）排放量单位为 tCO2，保留到小数点后两位；
//    e）主要工序产品产量单位为 t，保留到小数点后两位；
    private void displayData(ReportProductData reportProductData){
        int pointNum = 0;
        if(reportProductData.getItemRemark().contains("input") || reportProductData.getItemRemark().contains("emission")
                || reportProductData.getItemRemark().contains("esj")|| reportProductData.getItemRemark().contains("output")){
            pointNum = 2;
        }else if(reportProductData.getItemRemark().contains("fever")){
            pointNum = 3;
        }
        if(pointNum != 0){
            reportProductData.setMonth1(fixedDigitalNumber(reportProductData.getMonth1(), pointNum));
            reportProductData.setMonth2(fixedDigitalNumber(reportProductData.getMonth2(), pointNum));
            reportProductData.setMonth3(fixedDigitalNumber(reportProductData.getMonth3(), pointNum));
            reportProductData.setMonth4(fixedDigitalNumber(reportProductData.getMonth4(), pointNum));
            reportProductData.setMonth5(fixedDigitalNumber(reportProductData.getMonth5(), pointNum));
            reportProductData.setMonth6(fixedDigitalNumber(reportProductData.getMonth6(), pointNum));
            reportProductData.setMonth7(fixedDigitalNumber(reportProductData.getMonth7(), pointNum));
            reportProductData.setMonth8(fixedDigitalNumber(reportProductData.getMonth8(), pointNum));
            reportProductData.setMonth9(fixedDigitalNumber(reportProductData.getMonth9(), pointNum));
            reportProductData.setMonth10(fixedDigitalNumber(reportProductData.getMonth10(), pointNum));
            reportProductData.setMonth11(fixedDigitalNumber(reportProductData.getMonth11(), pointNum));
            reportProductData.setMonth12(fixedDigitalNumber(reportProductData.getMonth12(), pointNum));
            reportProductData.setYearvalue(fixedDigitalNumber(reportProductData.getYearvalue(), pointNum));
        }

    }
    private Double fixedDigitalNumber(Double number, int pointNum){
        if( number!= null){
            if(pointNum == 3){
                return Math.round(number * 1000.0) / 1000.0;
            }else if(pointNum == 2){
                return Math.round(number * 100.0) / 100.0;
            }
            return number;
        }else{
            return number;
        }
    }
}
